import random
import time
import requests
import json
from datetime import datetime, timedelta
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 配置
BASE_URL = "http://localhost:5000"  # 修改为实际的服务器地址
DEVICE_ID = "CQUCHX0503001"  # 修改为实际的设备ID
USER_ID = "1"  # 修改为实际的用户ID

# 模拟数据
SONGS = [
    {"id": "1", "name": "Song 1", "artists": [{"id": "1", "name": "Artist 1"}], "duration": 180000},
    {"id": "2", "name": "Song 2", "artists": [{"id": "2", "name": "Artist 2"}], "duration": 240000},
    {"id": "3", "name": "Song 3", "artists": [{"id": "3", "name": "Artist 3"}], "duration": 200000},
]

def generate_device_status():
    """生成设备状态数据"""
    return {
        "device_id": DEVICE_ID,
        "timestamp": int(time.time() * 1000),
        "Power": {
            "state": random.choice(["ON", "OFF"]),
            "battery_level": random.randint(0, 100),
            "isCharging": random.choice(["Charging", "Discharging", "Full"])
        },
        "Net": {
            "Wifi_state": "Connected",
            "net_delay": random.randint(10, 100)
        },
        "Audio": {
            "effect": random.choice(["Normal", "Bass", "Treble"]),
            "mode": random.choice(["Music", "Movie", "Game"])
        }
    }

def generate_listen_data():
    """生成听歌数据"""
    song = random.choice(SONGS)
    return {
        "device_id": DEVICE_ID,
        "user_id": USER_ID,
        "timestamp": int(time.time() * 1000),
        "song_name": song["name"],
        "id": song["id"],
        "artists": song["artists"],
        "dt": song["duration"]
    }

def send_data():
    """发送数据到服务器"""
    try:
        # 生成并发送听歌数据
        listen_data = generate_listen_data()
        response = requests.post(
            f"{BASE_URL}/v2/data",
            json=listen_data,
            headers={"Content-Type": "application/json"}
        )
        
        if response.status_code == 200:
            logger.info(f"听歌数据发送成功: {listen_data}")
        else:
            logger.error(f"听歌数据发送失败: {response.text}")
        
        # 生成并发送设备状态
        status_data = generate_device_status()
        response = requests.post(
            f"{BASE_URL}/v1/update_status",
            json=status_data,
            headers={"Content-Type": "application/json"}
        )
        
        if response.status_code == 200:
            logger.info(f"设备状态发送成功: {status_data}")
        else:
            logger.error(f"设备状态发送失败: {response.text}")
            
    except Exception as e:
        logger.error(f"发送数据异常: {str(e)}")

def main():
    """主函数"""
    logger.info("开始生成数据...")
    
    # 模拟设备注册
    try:
        register_data = {
            "device_id": DEVICE_ID,
            "device_key": "device_secret_key_123"
        }
        response = requests.post(
            f"{BASE_URL}/v1/device_register",
            json=register_data,
            headers={"Content-Type": "application/json"}
        )
        
        if response.status_code == 201:
            logger.info("设备注册成功")
        else:
            logger.error(f"设备注册失败: {response.text}")
    except Exception as e:
        logger.error(f"设备注册异常: {str(e)}")
    
    # 模拟设备激活
    try:
        activate_data = {
            "device_id": DEVICE_ID,
            "activation_code": f"{DEVICE_ID[:8]}-ACTIVE"
        }
        response = requests.post(
            f"{BASE_URL}/v1/activate_device",
            json=activate_data,
            headers={"Content-Type": "application/json"}
        )
        
        if response.status_code == 200:
            logger.info("设备激活成功")
        else:
            logger.error(f"设备激活失败: {response.text}")
    except Exception as e:
        logger.error(f"设备激活异常: {str(e)}")
    
    # 持续发送数据
    while True:
        send_data()
        time.sleep(5)  # 每5秒发送一次数据

if __name__ == "__main__":
    main() 